/*
 * @Author: ajun tangdunjun@guoxintianyu.com
 * @Date: 2023-05-04 16:29:34
 * @LastEditors: ajun tangdunjun@guoxintianyu.com
 * @LastEditTime: 2023-05-08 15:26:21
 * @FilePath: \lighthouse\src\pages\base\home\index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { defineComponent, ref, reactive, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElRow,
  ElCol,
  ElSelect,
  ElOption,
  ElCard,
  ElSpace,
  ElDivider,
  ElLink,
  ElTooltip,
  ElImage,
  ElIcon,
  ElScrollbar,
  ElMessage,
  ElLoading
} from 'element-plus'
import { ArrowDownBold, ArrowUpBold, Plus, Minus } from '@element-plus/icons-vue'
import type { HomeStateType, HomePatternDataType } from './typings'
import type { LoadingInstance } from 'element-plus/es/components/loading/src/loading'
import HomeMap from './HomeMap'
import styles from './index.module.scss'
import AliIcon from '~/components/AliIocn'
import SaasTitle from '~/components/SaasTitle'
import BaseStation from '../../assetManagement/components/assetHomeComponents/BaseStation'
import SetLamppostScope from '../distribution/SetLamppostScope'
import ConstructionOptions from '../construction/option'
import CabinetOptions from '../cabinet/option'
import ElectricityOptions from '../electricity/option'
import BaseStationOptions from '../data/option'

export default defineComponent({
  name: 'BasestationHome',
  setup: () => {
    const store = useStore()
    const homeMapRef = ref()
    const loadRef = ref<LoadingInstance>()
    const state = reactive<HomeStateType>({
      mapInputValue: 1,
      rowsNum: 1,
      graphicExampleExpand: false,
      mapZoom: 5,
      satelliteChangingOverShow: false,
      setLamppostScopeShow: false,
      labelsLayerList: [],
      constructionOptionsVisible: false,
      assetId: '',
      markerShowDetail: [],
      polygonShowDetail: [],
      baseCabinetVisible: false,
      baseElectricityVisible: false,
      baseStationVisible: false
    })

    // 获取当前页面初始化所需要的地图数据
    const initCallback = async () => {
      const { code, data } = await store.dispatch('base/GetAssetHomeMapSpecialTenant')
      if (code === 200) {
        state.cityName = data.city
        homeMapRef.value.handleSetMapInfo(data)
        //  图例状态数据
        data.specialDetailVOS.forEach((item: any) => {
          item.modelConfigDataVO.renderer.categoryList.forEach((row: any) => {
            if (item.assetModuleCode === 'WorkArea') {
              //  工区
              state.polygonShowDetail!.push({
                name: item.assetModuleName,
                moduleId: item.assetModuleId,
                status: row.value,
                color: row.color,
                check: true
              })
            } else {
              //  其它
              state.markerShowDetail!.push({
                name: item.assetModuleName,
                moduleId: item.assetModuleId,
                status: row.value,
                iconImage: row.iconImage,
                check: true
              })
            }
          })
        })

        //  图例
        state.patternData = data.specialDetailVOS.map((item: HomePatternDataType) => item)
        //  图例配置
        state.markerIconOptions = data.specialDetailVOS?.reduce(
          (markerIconOptions: any, item: any) => {
            markerIconOptions![item.assetModuleId] = {
              key: item.modelConfigDataVO?.renderer?.categoryList?.[0]?.select,
              isTag: item.modelConfigDataVO?.base?.isTag,
              tagName: item.modelConfigDataVO?.base?.tagName,
              legend: item.modelConfigDataVO?.base?.legend,
              infoVisible: item.modelConfigDataVO?.info?.infoVisible,
              zooms: item.modelConfigDataVO?.base?.maxScale
                ? [
                    item.modelConfigDataVO?.base?.minScale,
                    Math.floor(item.modelConfigDataVO?.base?.maxScale) + 0.9
                  ]
                : [],
              icons: item.modelConfigDataVO?.renderer?.categoryList?.reduce(
                (markerItemOption: Record<string, Record<string, any>>, childItem: any) => {
                  markerItemOption![childItem.value] = {
                    width: childItem.iconWidth,
                    height: childItem.iconLength,
                    iconUrl: childItem.iconImageBase,
                    iconSize: [childItem.iconWidth, childItem.iconLength],
                    offset: [0, -childItem.iconLength],
                    bigVisible: item.modelConfigDataVO?.select?.selectVisible,
                    bigWidth: item.modelConfigDataVO?.select?.selectIconWidth,
                    bigHeight: item.modelConfigDataVO?.select?.selectIconLength,
                    bigIconSize: [
                      item.modelConfigDataVO?.select?.selectIconWidth,
                      item.modelConfigDataVO?.select?.selectIconLength
                    ],
                    bigOffset: [
                      0,
                      -item.modelConfigDataVO?.select?.selectIconLength + childItem.iconLength
                    ],
                    color: childItem.color,
                    lineColor: childItem.lineColor
                  }
                  return markerItemOption
                },
                {}
              )
            }
            return markerIconOptions
          },
          {}
        )

        homeMapRef.value.trendsLabelsLayer(state.markerIconOptions)
        allMarkerLabelsLayerAjax()
        getWorkAreaList()
      } else {
        getMapZoom()
      }
    }
    //  显示全部地图数据
    const allMarkerLabelsLayerAjax = async () => {
      loadRef.value = ElLoading.service({
        target: '#loadRef',
        background: 'rgba(255, 255, 255, .2)',
        text: '加载中'
      })
      const { code, data } = await store.dispatch(
        'assetHome/GetAssetHomeBaseDataByModuleIdStationGisApi',
        {
          specialCode: 'basestation_home'
        }
      )
      if (code === 200 && data.length > 0) {
        state.labelsLayerList = data?.filter((item: { phase: any }) => item.phase)
        homeMapRef.value.markerLabelsLayer(data)
        // homeMapRef.value.handleSetMapInfo({
        //   lon: state.labelsLayerList![0].phase.coordinates[0],
        //   lat: state.labelsLayerList![0].phase.coordinates[1]
        // })
        loadRef.value!.close()
      } else {
        homeMapRef.value.markerLabelsLayer([])
      }
      loadRef.value!.close()
    }
    //  地图数据
    const markerLabelsLayerAjax = async (obj?: any) => {
      loadRef.value = ElLoading.service({
        target: '#loadRef',
        background: 'rgba(255, 255, 255, .2)',
        text: '加载中'
      })
      const showDetail = state.markerShowDetail?.filter((item) => item.check)
      const { code, data } = await store.dispatch(
        'assetHome/GetAssetHomeBaseDataByModuleIdStationGisApi',
        {
          specialCode: 'basestation_home',
          showDetail,
          ...obj
        }
      )
      if (code === 200) {
        // 需要显示的数据
        const showList = data.map((element: any) => element.id)
        // 需要隐藏的数据
        const hideList = state
          .labelsLayerList!.filter((element: any) => {
            return showList.indexOf(element.id) === -1
          })
          .map((element: any) => element.id)
        homeMapRef.value.setMarkersVisible(showList, hideList)

        //  清空点击标点 关闭弹框
        homeMapRef.value.selectedMarkerRemove()
        handleCancelPatternMarkerPopover()

        loadRef.value!.close()

        if (data.length === 0) {
          ElMessage({ type: 'warning', message: '未匹配到数据' })
        } else {
          homeMapRef.value.handleSetMapInfo({
            layerLevel: 14,
            lon: data![0].phase.coordinates[0],
            lat: data![0].phase.coordinates[1]
          })
        }
      }
    }
    //  获取工区数据
    const getWorkAreaList = async () => {
      const { code, data } = await store.dispatch('base/GetWorkAreaList')
      if (code === 200) {
        data?.map((item: any) => {
          if (item?.phase) {
            const phase = JSON.parse(item?.phase)
            homeMapRef.value.handleGeneratePolygon({
              ...item,
              phaseType: phase?.type || '',
              coordinates: phase?.coordinates || [],
              zooms: state.markerIconOptions![item.moduleId].zooms
            })
          }
          return item.id
        })
      }
    }
    // 查询租户专题图(按钮操作栏)
    const handleGetOptionsBar = async () => {
      const { code, data } = await store.dispatch('base/GetAssetHomeOptionsBar')
      if (code === 200) {
        data.forEach((item: any) => {
          item.check = true
        })
        state.optionsBar = data || []
      }
    }
    //  图例显隐 (点)
    const markerLegendClick = (item: any) => {
      item.check = !item.check
      if (state.mapInputValue === 1) {
        handleBatchNumChange()
      } else {
        markerLabelsLayerAjax({ keyword: state.keyword })
      }
    }
    //  图例显隐 (面)
    const polygonLegendClick = (item: any) => {
      item.check = !item.check
      homeMapRef.value.polygonLegend(item)
    }
    //  地图数据更新
    // const handleSearchMapMarkerByModuleId = () => {
    //   const bounds = homeMapRef.value.map.getBounds()
    //   const northEast = [bounds.northEast.lng, bounds.northEast.lat]
    //   const southEast = [bounds.southWest.lng, bounds.northEast.lat]
    //   const southWest = [bounds.southWest.lng, bounds.southWest.lat]
    //   const northWest = [bounds.northEast.lng, bounds.southWest.lat]
    //   const screenHouseList = state.labelsLayerList!.filter((item: any) => {
    //     return homeMapRef.value.aMap.GeometryUtil.isPointInRing(item.phase.coordinates, [
    //       northEast,
    //       southEast,
    //       southWest,
    //       northWest
    //     ])
    //   })
    //   homeMapRef.value.markerLabelsLayer(screenHouseList)
    // }
    //  操作栏
    const handleChangeActiveOptionsBar = (value: any) => {
      value.check = !value.check
      const moduleIds = state.optionsBar
        ?.filter((item: any) => item.check)
        .map((item: any) => item.id)
      value.code === 'WorkArea'
        ? homeMapRef.value.polygonLabelsLayerSwitch(value.check)
        : homeMapRef.value.markerLabelsLayerSwitch(moduleIds)

      //  清空点击标点 关闭弹框
      homeMapRef.value.selectedMarkerRemove()
      handleCancelPatternMarkerPopover()

      //  清空圆、灯杆
      homeMapRef.value.drawCircleCrea()
    }

    // 获取当前地图层级并赋值
    const getMapZoom = () => {
      state.mapZoom = Math.round(homeMapRef.value.map.getZoom())
    }

    //  回车搜索地区
    const handleDistribution = (e: Event | KeyboardEvent) => {
      if ((e as KeyboardEvent).key !== 'Enter') return
      handleSearchDistribution()
    }
    const handleSearchDistribution = () => {
      if (state.positionName) {
        homeMapRef.value.handleSearchDistribution(state.positionName)
      }
    }
    //  点位显示弹框
    const changePatterMarkerInfoView = (left: number, top: number, type: any, info: any) => {
      state.patternMarkerType = type
      state.patternMarkerInfo = info
        ? {
            popoverInfo: info,
            left,
            top
          }
        : undefined
    }
    //  更新弹框位置
    const changePatterMarkerInfoPosition = (left: number, top: number) => {
      if (!state.patternMarkerInfo) return
      state.patternMarkerInfo!.left = left
      state.patternMarkerInfo!.top = top
    }
    //  关闭单框
    const handleCancelPatternMarkerPopover = () => {
      state.patternMarkerType = undefined
      state.patternMarkerInfo = undefined
    }
    //  获取点击详情经纬度
    const phase = reactive({ lat: 0, lon: 0 })
    const onGetMarkerInfo = (value: any) => {
      phase.lat = value.phase.coordinates[1]
      phase.lon = value.phase.coordinates[0]
    }
    //  周边灯杆 圆
    const onAmbitusLamp = async () => {
      handleCancelPatternMarkerPopover()
      const res1 = await store.dispatch('base/GetLampPostScope')
      if (res1.code === 200) {
        await homeMapRef.value.drawCircle(res1?.data, [phase.lon, phase.lat])
      }
      const res = await store.dispatch('base/GetLampPostByscope', {
        lat: phase.lat,
        lon: phase.lon
      })
      if (res.code === 200) {
        homeMapRef.value.appendixLamppostDraw(res?.data)
      }
    }
    // 设置灯杆范围
    const onSetLamppostScope = () => {
      state.setLamppostScopeShow = !state.setLamppostScopeShow
      handleCancelPatternMarkerPopover()
    }
    //  设置灯杆范围
    const onSetHandleChange = async (scope: string) => {
      const res = await store.dispatch('base/SetLampPostScope', { scope })
      if (res.code === 200) {
        ElMessage({ type: 'success', message: res.msg })
        homeMapRef.value.drawCircleCrea()
        onAmbitusLamp()
      }
    }

    //  地图数据搜索
    const onBatchNum = (value: number) => {
      state.rowsNum = value
    }
    const mapInputValueChange = () => {
      state.batchNum = []
      state.keyword = ''
    }
    const handleSearchPowerDistributionFacilitie = (e: Event | KeyboardEvent) => {
      if ((e as KeyboardEvent).key !== 'Enter') return
      markerLabelsLayerAjax({ keyword: state.keyword })
    }
    const handleBatchNumChange = () => {
      const batchNum = state.batchNum?.join(',')
      markerLabelsLayerAjax({ batchNum })
    }
    //  批次搜索
    const remoteMethod = async (query: string) => {
      if (query) {
        const { code, data } = await store.dispatch('base/GetSelectBatchNumListBox', {
          batchNum: query
        })
        if (code === 200) {
          state.SelectListCode = data
        } else {
          state.SelectListCode = []
        }
      }
    }

    // 控制地图放大缩小
    const handleClickChangeMapZoom = async (type: '+' | '-') => {
      if (type === '+') {
        state.mapZoom++
      } else {
        state.mapZoom--
      }
      await homeMapRef.value.map.setZoom(state.mapZoom)
    }

    //  卫星图是否展示
    const satelliteChangingOver = () => {
      state.satelliteChangingOverShow = !state.satelliteChangingOverShow
      homeMapRef.value.satelliteChangingOver(state.satelliteChangingOverShow)
    }

    // 图例card是否展开
    const handleChangeGraphicExampleExpand = () => {
      state.graphicExampleExpand = !state.graphicExampleExpand
    }

    //  查看详情
    const onConstructionInfo = (value: any) => {
      handleCancelPatternMarkerPopover()
      state.assetId = value.assetId
      if (value.moduleCode === 'BaseCabinet') {
        //  机柜
        state.baseCabinetVisible = true
      } else if (value.moduleCode === 'BaseElectricity') {
        //  电表
        state.baseElectricityVisible = true
      } else if (value.moduleCode === 'BaseStation') {
        //  基站
        state.baseStationVisible = true
      } else {
        //  站址
        state.constructionOptionsVisible = true
      }
    }

    onMounted(() => {
      handleGetOptionsBar()
      //  查勘状态
      store.dispatch('base/SurveyStatusGet', { code: 'asset_station_survey' })
      //  基站状态
      store.dispatch('base/BaseStatusGet', { code: 'asset_station_isdeliver' })
      //  运营商
      store.dispatch('base/OperatorGet', { code: 'asset_station_infoserver' })
      //  是否共享
      store.dispatch('base/ShareGet', { code: 'asset_station_share' })
    })

    const router = useRouter()
    watch(
      () => router.currentRoute.value,
      () => {
        state.patternMarkerType = undefined
      }
    )

    return () => {
      return (
        <section class={styles['asset-home-box']}>
          <HomeMap
            id={styles['asset-home-map']}
            ref={homeMapRef}
            initCallback={initCallback}
            getMapZoom={getMapZoom}
            markerIconOptions={state.markerIconOptions}
            onChangePatterMarkerInfoView={changePatterMarkerInfoView}
            onChangePatterMarkerInfoPosition={changePatterMarkerInfoPosition}
            // onHandleSearchMapMarkerByModuleId={handleSearchMapMarkerByModuleId}
            onGetMarkerInfo={onGetMarkerInfo}
          />
          {/* 搜索栏 */}
          <section class={styles['asset-home-search']}>
            <ElForm class={styles['asset-home-search-form']}>
              <ElFormItem class={styles['asset-home-search-form-item']}>
                <ElInput
                  v-model={state.positionName}
                  clearable
                  placeholder="请输入地区"
                  prefixIcon={<AliIcon type="icon-sousuo" />}
                  onKeydown={handleDistribution}
                  onClear={handleSearchDistribution}
                />
              </ElFormItem>
              <ElFormItem class={styles['asset-home-search-form-item']} style="width: 360px;">
                <ElRow>
                  <ElCol span={8}>
                    <ElSelect
                      v-model={state.mapInputValue}
                      onChange={mapInputValueChange}
                      style="width: 120px;"
                    >
                      <ElOption label="需求批次" value={1}></ElOption>
                      <ElOption label="关键字" value={2}></ElOption>
                    </ElSelect>
                  </ElCol>
                  <ElCol span={16}>
                    {state.mapInputValue === 2 ? (
                      <ElInput
                        v-model={state.keyword}
                        {...{ rows: state.rowsNum }}
                        placeholder="站点名称/灯杆名称/匹配站名 回车批量搜索"
                        onKeydown={handleSearchPowerDistributionFacilitie}
                        onFocus={() => onBatchNum(4)}
                        onBlur={() => onBatchNum(1)}
                        type="textarea"
                        style="position: absolute; top: 2px; left: 120px; z-index: 99;width: 240px;"
                      />
                    ) : (
                      <ElSelect
                        v-model={state.batchNum}
                        multiple
                        collapse-tags
                        collapse-tags-tooltip
                        placeholder="需求批次"
                        filterable
                        remote
                        reserve-keyword
                        remote-method={remoteMethod}
                        onChange={handleBatchNumChange}
                        style="position: absolute; top: 2px; left: 120px; z-index: 99;width: 240px;"
                      >
                        {state.SelectListCode?.map((item: string) => (
                          <ElOption key={item} label={item} value={item} />
                        ))}
                      </ElSelect>
                    )}
                  </ElCol>
                </ElRow>
              </ElFormItem>
            </ElForm>
          </section>
          {/* 按钮操作栏 */}
          {!!state.optionsBar?.length && (
            <ElCard
              class={{
                [styles['asset-home-options-bar']]: true
              }}
            >
              <ElSpace spacer={<ElDivider direction="vertical" />}>
                {state.optionsBar?.map((item) => (
                  <ElLink
                    style={{ display: 'block' }}
                    underline={false}
                    onClick={() => handleChangeActiveOptionsBar(item)}
                  >
                    <ElTooltip effect="light" placement="top" content={item?.name}>
                      <img
                        class={styles['asset-home-options-bar-icon']}
                        src={item.check ? item.iconUrl : item.greyIconUrl}
                      />
                    </ElTooltip>
                  </ElLink>
                ))}
              </ElSpace>
            </ElCard>
          )}
          {/* 控制地图放大缩小 */}
          <section
            // direction="vertical"
            class={{
              [styles['asset-home-zoom']]: true,
              [styles['asset-home-zoom-expand']]: state.graphicExampleExpand
            }}
          >
            <ElCard class="zoom-number-card">{state.mapZoom}</ElCard>
            <ElCard class="zoom-option-card">
              <ElSpace direction="vertical" spacer={<ElDivider />}>
                <ElLink
                  underline={false}
                  icon={Plus}
                  disabled={state.mapZoom === 20}
                  onClick={() => handleClickChangeMapZoom('+')}
                />
                <ElLink
                  underline={false}
                  icon={Minus}
                  disabled={state.mapZoom === 5}
                  onClick={() => handleClickChangeMapZoom('-')}
                />
              </ElSpace>
            </ElCard>
          </section>
          {/* 卫星地图切换 */}
          <div
            class={{
              [styles['asset-home-zoom-over']]: true,
              [styles['asset-home-zoom-over-actions']]: state.satelliteChangingOverShow
            }}
            onClick={satelliteChangingOver}
          >
            <AliIcon type="icon-a-weixinghangtiantianwen1" />
            &nbsp;卫星
          </div>
          {/* 图例展示栏 */}
          <ElCard
            class={{
              [styles['asset-home-graphic-example']]: true,
              [styles['asset-home-graphic-example-packUp']]: !state.graphicExampleExpand
            }}
            v-slots={{
              header: () => (
                <ElRow>
                  <ElCol span={12}>
                    <SaasTitle type="primary">图例</SaasTitle>
                  </ElCol>
                  <ElCol span={12} {...{ align: 'right' }}>
                    <ElLink underline={false} onClick={handleChangeGraphicExampleExpand}>
                      <ElIcon>
                        {state.graphicExampleExpand ? <ArrowDownBold /> : <ArrowUpBold />}
                      </ElIcon>
                    </ElLink>
                  </ElCol>
                </ElRow>
              )
            }}
          >
            <ElScrollbar height={327}>
              <ElSpace direction="vertical" fill size={16}>
                {/* 工区 */}
                {state.polygonShowDetail?.map((item: any) => (
                  <ElSpace style="cursor: pointer;">
                    <AliIcon
                      class={styles['asset-home-graphic-example-icon']}
                      type="icon-gongqu"
                      color={item.color}
                    />
                    <section
                      class={{
                        'text-one-line-overflow': true,
                        [styles['asset-home-graphic-example-text']]: !item.check
                      }}
                      onClick={() => polygonLegendClick(item)}
                    >
                      {item.name}（{item.status}）
                    </section>
                  </ElSpace>
                ))}
                {/* 其它 */}
                {state.markerShowDetail?.map((item: any) => (
                  <ElSpace style="cursor: pointer;">
                    <ElImage
                      class={styles['asset-home-graphic-example-icon']}
                      src={item.iconImage}
                    />
                    <section
                      class={{
                        'text-one-line-overflow': true,
                        [styles['asset-home-graphic-example-text']]: !item.check
                      }}
                      onClick={() => markerLegendClick(item)}
                    >
                      {item.name}（{item.status}）
                    </section>
                  </ElSpace>
                ))}
              </ElSpace>
            </ElScrollbar>
          </ElCard>
          {/* 基站信息弹框 */}
          {(state.patternMarkerType === 'BaseStation' ||
            state.patternMarkerType === 'BaseBuild' ||
            state.patternMarkerType === 'BaseCabinet' ||
            state.patternMarkerType === 'BaseElectricity') && (
            <BaseStation
              {...(state.patternMarkerInfo || {})}
              onCancel={handleCancelPatternMarkerPopover}
              // changeActivePatternMarker={handleChangeActivePatternMarkerInfo}
              onSetLamppostScope={onSetLamppostScope}
              onAmbitusLamp={onAmbitusLamp}
              onConstructionInfo={onConstructionInfo}
            />
          )}
          {/* 范围设置 */}
          {state.setLamppostScopeShow && (
            <SetLamppostScope
              visible={state.setLamppostScopeShow}
              onClose={onSetLamppostScope}
              onHandleChange={onSetHandleChange}
            />
          )}
          {/* 点位详情 */}
          {state.constructionOptionsVisible && (
            <ConstructionOptions
              style="position: absolute; top: 0; left: 0; z-index: 999;"
              record={{ id: state.assetId }}
              type="read"
              cancel={() => {
                state.constructionOptionsVisible = false
              }}
            />
          )}
          {/* 机柜详情 */}
          {state.baseCabinetVisible && (
            <CabinetOptions
              style="position: absolute; top: 0; left: 0; z-index: 999;"
              record={{ id: state.assetId }}
              type="update"
              cancel={() => {
                state.baseCabinetVisible = false
              }}
            />
          )}
          {/* 电表详情 */}
          {state.baseElectricityVisible && (
            <ElectricityOptions
              style="position: absolute; top: 0; left: 0; z-index: 999;"
              record={{ id: state.assetId }}
              type="update"
              cancel={() => {
                state.baseElectricityVisible = false
              }}
            />
          )}
          {/* 基站详情 */}
          {state.baseStationVisible && (
            <BaseStationOptions
              style="position: absolute; top: 0; left: 0; z-index: 999;"
              record={{ id: state.assetId }}
              type="update"
              cancel={() => {
                state.baseStationVisible = false
              }}
            />
          )}
        </section>
      )
    }
  }
})
